<template>
  <div class="search-result">
    <van-list
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
          :error.sync="error"
          error-text="加载失败，请点击重试"
        >
    <van-cell v-for="(article,index) in list"
     :key="index"
      :title="article.title"
      />
  </van-list>
  </div>
</template>

<script>
import { getSearchResult } from '@/api/search.js'
export default {
  name: 'SearchResult',
  props: {
    searchText: {
      type: String,
      require: true
    }
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      page: 1,
      perPage: 20,
      error: false
    }
  },

  mounted () {

  },

  methods: {
    async  onLoad () {
      try {
        // 获取数据
        const { data } = await getSearchResult({
          page: this.page, // 页码
          per_page: this.perPage, // 每页大小
          q: this.searchText// 查询关键词
        })
        // 数据添加到数组
        const { results } = data.data

        this.list.push(...results)
        // loading状态关闭
        this.loading = false
        if (results.length) {
          // 有数据，获取下一个页码
          this.page++
        } else {
          // 没有数据，显示完成状态 没有更多数据
          this.finished = true
        }
      } catch (err) {
        // 加载失败的提示
        this.error = false
        this.loading = false
        this.$toast('数据加载失败')
      }
    }
  }
}
</script>

<style lang="less" scoped>

</style>
